#! /usr/bin/env python
# -*- coding: utf8 -*-

# This program had features added quickly. My ICE was between 180 km/h and
# 240 km/h while I coded this! Talk about fast programming....

# Dies Program war sehr schnell programmiert. Zwischen 180 km/h und 240 km/h,
# als habe ich es auf einem ICE Zug korrigiert ;)

from xml.etree.ElementTree import parse
import pydot
import sys

g = pydot.Dot(name=sys.argv[1].split("/")[-1], type='digraph', suppress_disconnected=True)
r = parse(sys.argv[1]).getroot()

elements = [r] + r.findall(".//*")
nodes = dict([(x, pydot.Node(name="n%d" % (id(x),))) for x in elements])
edges = []
txt_nodes = []
attr_nodes = []
attr_txt   = []


for xml_node, graph_node in nodes.iteritems():
    graph_node.set_label(xml_node.tag)
    if xml_node.text != None and xml_node.text.strip() != "":
        nn = pydot.Node(name="t%d" % (id(xml_node),))
        nn.label = xml_node.text.strip()
        nn.shape = "none"
        txt_nodes.append(nn)
        edges.append(pydot.Edge(graph_node.name, nn.name))
        continue
    for n in xml_node[:]:
        edges.append(pydot.Edge(graph_node.name, nodes[n].name))
    for name, content in xml_node.attrib.iteritems():
        nn = pydot.Node(name="a%d%s" % (id(xml_node), name))
        nn.label = name.strip()
        nn.shape = "box"
        attr_nodes.append(nn)

        at = pydot.Node(name="v%d%s"  % (id(xml_node), name))
        at.label = content.strip()
        at.shape = "none"
        attr_txt.append(at)

        edges.append(pydot.Edge(graph_node.name, nn.name))
        edges.append(pydot.Edge(nn.name, at.name))

map(g.add_node, nodes.values()[::-1] + txt_nodes)
map(g.add_node, attr_nodes)
map(g.add_node, attr_txt)
map(g.add_edge, edges)

print g.to_string()
